<template>
  <div class="login">
    <el-form :model="form" label-width="100px" class="login-form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="账号" prop="username">
        <v-input v-model="form.username" type="text" placeholder="请输入账号" :width="350"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <v-input
            v-model="form.password"
            type="password"
            isShowPassword
            placeholder="请输入密码"
            :width="350"
        />
      </el-form-item>
      <el-form-item>
        <v-button type="primary" @click="onSubmit" text="登录" :loading="loading"></v-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import {reactive, ref, inject} from 'vue'
import type {FormInstance} from 'element-plus'
import {useRouter, useRoute} from 'vue-router'
import useUserStore from '@/store/modules/user'
import {SET_TOKEN} from '@/utils/storage'
import {LoginApi} from "@/api/user";

let $message: any = inject('$message')

const userStore = useUserStore()
const $router = useRouter()
const $route = useRoute();

const form = reactive({
  username: '',
  password: ''
})
const loading = ref(false)
const rules = reactive({
  username: [{required: true, message: '请输入账号', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}]
})
const ruleFormRef = ref<FormInstance>()
const onSubmit = () => {
  ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            const res = await LoginApi(form)
            if (res.status === 0) {
              $message({
                message: '登陆成功',
                type: 'success',
              })
              //第一种修改store的方法
              // userStore.token =  res.data.token
              //第二种修改store的方法，可以修改多个
              userStore.$patch({
                token: res.data.token
              })
              SET_TOKEN(res.data.token)
              await userStore.getUserInfo()
              let redirect: any = $route.query.redirect;
              if (redirect) {
                await $router.push(redirect)
              } else {
                await $router.push('/home')
              }
            } else {
              $message({
                message: res.msg,
                type: 'error',
              })
              loading.value = false
            }
          } catch (e) {
            console.log(e);
            loading.value = false
          }

        }
      }
  )
}
</script>
<style scoped lang="scss">
.login {
  background: url("../../assets/images/login.jpg") no-repeat;
  width: 100%;
  height: 100vh;
  background-size: cover;

  .login-form {
    width: 600px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
